import { defineComponent, onMounted, ref } from "vue";
import "./css/style.css";
import Child from "./child";

// 函数式组件
function FunComponent(props, { emit }) {
  return (
    <div>
      我是函数式组件
      <div>msg:{props.msg}</div>
      <button onClick={() => emit("childBtnClick", "我是函数式子组件的数据")}> 事件传递给父组件</button>
    </div>
  );
}

export default defineComponent({
  setup() {
    const msg = ref("Hello JSX");
    const num = ref(1);
    const flag = ref(true);
    const list = ref([
      { id: 1, name: "张三" },
      { id: 2, name: "李四" },
      { id: 3, name: "王五" },
    ]);
    const btnClick = () => {
      num.value++;
    };

    // 子组件传递事件
    const childBtnClick = (val) => {
      ElMessage.success(val);
    };

    // 模板引用
    const divRef = ref();
    

    onMounted(() => {
        console.log("divRef", divRef.value); //页面加载完后才能获取到模板引用
    });

    return () => (
      <div>
        <h1>hello jsx</h1>
        <div className="msg">{msg.value}</div>
        <div>
          num :<span style={{ color: "red" }}>{num.value}</span>
        </div>
        <button onClick={btnClick}>按钮</button>
        <hr />
        <div style={{ color: "yellow" }}>v-if用法：</div>
        <div>{flag.value ? "flag is true" : <span>flag is false</span>}</div>
        <button onClick={() => (flag.value = !flag.value)}>切换flag</button>

        <hr />
        <div style={{ color: "yellow" }}>v-for用法：</div>
        <ul>
          {list.value.map((item, i) => {
            return <li key={i}>{item.name}</li>;
          })}
        </ul>

        <hr />
        {/* 组件传值、插槽 */}
        <div style={{ color: "yellow" }}>子组件</div>
        <Child title="固定参数传递" num={num.value} onBtnClick={childBtnClick}>
          {{
            default: (props) => "默认插槽----" + props,
            title: (props) => "具名插槽----" + props,
          }}
        </Child>

        <hr />
        {/* 模板引用 */}
        <div style={{ color: "yellow" }}>模板引用</div>
        <div ref={divRef}>ref测试</div>

        <hr />
        <div style={{ color: "yellow" }}>函数式组件</div>
        <FunComponent
          msg="函数式组件"
          onChildBtnClick={(val) => {
            ElMessage.success(val);
          }}
        ></FunComponent>
      </div>
    );
  },
});
